//
//  YHY_Search_ViewController.m
//  Travels
//
//  Created by yanghuiyan on 16/3/16.
//  Copyright © 2016年 yanghuiyan. All rights reserved.
//

#import "YHY_Search_ViewController.h"
#import "YHY_TravelDetail_VC.h"
#import "YHYAFNetTool.h"
#import "SearchModel.h"
#import "YHY_TravelNotesTableViewCell.h"
#import "YHYBaseTableView.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#define Width self.view.bounds.size.width
#define Height self.view.bounds.size.height
@interface YHY_Search_ViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISearchBar *mySearchBar;

@property (nonatomic, retain) NSMutableArray *dataSource;

@property (nonatomic, retain) YHYBaseTableView *tableView;

@property (nonatomic, retain) MBProgressHUD *HUD;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, retain) UIImageView *bacImageView;

@end

@implementation YHY_Search_ViewController

- (void)dealloc {
    
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    _mySearchBar.delegate = nil;
    [_mySearchBar release];
    [_dataSource release];
    [_tableView release];
    [super dealloc];
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationController.tabBarController.tabBar.hidden = YES;
    
//    self.navigationController.navigationBar.translucent = YES;
    self.dataSource = [[NSMutableArray alloc] initWithCapacity:0];
    [self creatView];
//    [self GETData];
    
    self.bacImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Width, Height)];
    self.bacImageView.image = [UIImage imageNamed:@"搜索背景"];
    
    [self.bacImageView bringSubviewToFront:self.tableView];
    
    [self.tableView addSubview:self.bacImageView];

}

#pragma mark - 创建视图
- (void)creatView {
    
    //导航栏左侧按钮
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    [leftItem release];
    
    //创建tableView
    self.tableView = [[YHYBaseTableView alloc] initWithFrame:CGRectMake(0, 0, Width, Height) style:UITableViewStylePlain];
    [self.tableView registerClass:[YHY_TravelNotesTableViewCell class] forCellReuseIdentifier:@"TravelNotesTableViewCellIdentifier"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [_tableView release];
    
    //新建SearchBar  并设置代理人
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width - 120, 42)];
    self.mySearchBar.delegate = self;
    
    
    // 设置类型
    // 设置搜索框
    self.mySearchBar.barStyle = UIBarStyleDefault;
    // 设置键盘类型
    self.mySearchBar.keyboardType = UIKeyboardTypeDefault;
    // 设置搜索框内部文字
    self.mySearchBar.placeholder = @"请输入国家、地名、游记名称";
    self.mySearchBar.showsCancelButton = YES;
    self.navigationItem.titleView = self.mySearchBar;
    [_mySearchBar release];
    
    
}

#pragma mark - 左侧按钮点击事件
- (void) leftItemAction:(UIBarButtonItem *)button {
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.tabBarController.tabBar.hidden = NO;
    [self.mySearchBar resignFirstResponder];
}

#pragma mark - 实现UISearchBarDelegate协议方法
// 当点击search的时候调用
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [self.dataSource removeAllObjects];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    // 将搜索的文字存到字符串
    self.place = searchBar.text;
    self.page = 1;
    [self.tableView addFooterWithTarget:self action:@selector(GETData)];
    [self.tableView footerBeginRefreshing];
    self.tableView.footerPullToRefreshText = @"加载更多";
    self.tableView.footerRefreshingText = @"加载完成";
    self.tableView.footerReleaseToRefreshText = @"正在加载";
    
    // 点击搜索时 取消键盘响应
    [self.mySearchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.mySearchBar resignFirstResponder];
    [self.mySearchBar setShowsCancelButton:YES animated:YES];
    [self.dataSource removeAllObjects];
    [_tableView reloadData];
    
}

#pragma mark - UITableViewDataSource协议方法实现
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YHY_TravelNotesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TravelNotesTableViewCellIdentifier"];

    cell.searchModel = self.dataSource[indexPath.row];
    return cell;
}

// 返回高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200;
}

#pragma mark - 跳转下一页 搜索的游记详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    YHY_TravelDetail_VC *VC = [[YHY_TravelDetail_VC alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
   
    SearchModel *model = self.dataSource[indexPath.row];
    VC.idNew = model.idNew;
    
    [VC release];
 }


#pragma mark - 数据解析
- (void)GETData {
    
    [self loadPic];
    
    // 网址拼接搜索框输入的文字内容
    NSString *string = [NSString stringWithFormat:@"http://chanyouji.com/api/search/trips.json?page=%ld&q=%@", (long)self.page ,self.place];

    [YHYAFNetTool GETNetWirhUrl:string body:nil headerFile:nil response:YHYJSON Success:^(id result) {

        NSArray *array = (NSArray *)result;
        
        if (array.count == 0) {
            
            self.bacImageView.hidden = NO;
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            //设置类型
            hud.mode = MBProgressHUDModeText;
            
            //设置文字
            hud.labelText = @"啊噢,搜不到了~~";
            
            //出现时间
            [hud hide:YES afterDelay:3];


        } else {
            self.bacImageView.hidden = YES;
            
           
        }
            for (NSDictionary *dic in result) {
                SearchModel *searchModel = [[SearchModel alloc] initWithDataSource:dic];
                
                [self.dataSource addObject:searchModel];
            }
            self.page +=1;
            
            self.HUD.hidden = YES;
            
            [self.tableView reloadData];
            [self.tableView footerEndRefreshing];
    
        
    } Failure:^(NSError *error) {
        NSLog(@"fail");

        
    }];
}

#pragma mark - 数据加载图标
- (void)loadPic {
    
    //初始化
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    //设置文字
    self.HUD.labelText = @"努力加载中";
    
    //设置文字颜色
    self.HUD.labelColor = [UIColor whiteColor];
    
    //设置整体图标的颜色
    self.HUD.color = [UIColor grayColor];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
